<template>
  <div class="containner">
    <div style="display:flex;justify-content: space-around;align-items: center;" id="debug-select-container">
      <el-select v-model="deviceValue" @change="querylog">
        <el-option v-for="item in deviceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="processValue" @change="querylog" class="ml20">
        <el-option v-for="item in processOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="debugValue" @change="querylog" class="ml20" :append-to="customContainer">
        <el-option v-for="item in debugOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <div>
        <el-input v-model="searchKey" placeholder="请输入关键词" clearable @change="onSearch" @clear="onSearchClear" class="ml20 searchBoxLog width400">
          <template #prefix>
            <el-icon v-if="!searchLoading">
              <Search />
            </el-icon>
            <el-icon v-else class="is-loading">
              <Loading />
            </el-icon>
          </template>
        </el-input>
      </div>
      <div style="display:flex;justify-content: center;align-items: center;">
        <div class="ml20"><el-switch v-model="enableLogs"  size="large" @change="switchChange" /></div>
        <div class="ml5"><el-tooltip content="开关开启后，日志会被保存" effect="dark"><el-icon>
              <QuestionFilled />
            </el-icon></el-tooltip></div>
      </div>
    </div>
    <div ref="editorRef" class="monaco-editor" id="monacoEditorLog"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive, onBeforeUnmount } from 'vue';
import * as monaco from 'monaco-editor'
import { Loading } from '@element-plus/icons-vue'

// VSCode API 接口
declare global {
  interface Window {
    vscode: {
      postMessage: (message: any) => void;
    };
    initialRoute: string;
  }
}

let deviceOptions = reactive<string[]>([]);
let deviceValue = ref('');
let processOptions = reactive<{value: string, label: string}[]>([]);
let processValue = ref('');
let debugOptions = reactive<string[]>([]);
let debugValue = ref('');
let searchKey = ref('');
const enableLogs = ref(false);
const props = defineProps({
  modelValue: String,
  language: { type: String, default: 'javascript' },
  theme: { type: String, default: 'vs-dark' }
})
const editorRef = ref<HTMLElement>()
let editor: monaco.editor.IStandaloneCodeEditor
let deviceTimer: number | null = null;
let autoScroll = true; // 默认启用自动滚动
let userScrolling = false; // 跟踪用户是否正在滚动
let customContainer = ref<HTMLElement | null>(null);
let searchDebounceTimer: number | null = null; // 搜索防抖定时器
const searchLoading = ref(false); // 搜索状态

// 消息处理
const handleMessages = (event: MessageEvent) => {
  const message = event.data;
  
  switch (message.command) {
    case 'addLogs':
      // 更新日志内容
      if (editor && message.logs) {
        const currentContent = editor.getValue();
        const newContent = currentContent + message.logs;
        
        // 保存当前滚动位置和状态
        const isAtBottom = isEditorScrolledToBottom();
        
        // 更新内容
        editor.setValue(newContent);
        
        // 如果之前在底部或启用了自动滚动，则滚动到底部
        if (isAtBottom || (autoScroll && !userScrolling)) {
          scrollToBottom();
        }
      }
      break;
    case 'deviceList':
      // 更新设备列表
      if (message.devices && Array.isArray(message.devices)) {
        deviceOptions.length = 0;
        message.devices.forEach((device: string) => {
          deviceOptions.push(device);
        });
        
        // 如果当前没有选中设备但有可用设备，则自动选择第一个
        if ((!deviceValue.value || deviceOptions.indexOf(deviceValue.value) === -1) && deviceOptions.length > 0) {
          deviceValue.value = deviceOptions[0];
          querylog();
          
          // 如果有设备，停止定时请求
          stopDeviceListTimer();
        } else if (deviceOptions.length === 0) {
          // 如果没有设备，确保定时器正在运行
          startDeviceListTimer();
        }
      }
      break;
    case 'processList':
      if (message.processes && Array.isArray(message.processes)) {
        processOptions.length = 0;
        processOptions.push({ value: '全部进程', label: '全部进程' });
        message.processes.forEach((proc: {pid: string, name: string}) => {
            processOptions.push({ value: proc.pid, label: `${proc.name} (${proc.pid})` });
        });
        // Keep '全部进程' as default unless there's a reason to change
        if (!processOptions.some(p => p.value === processValue.value)) {
            processValue.value = '全部进程';
        }
      }
      break;
    case 'deviceDisconnected':
      // 设备断开连接通知
      console.log('Device disconnected');
      // 清空设备列表
      deviceOptions.length = 0;
      deviceValue.value = '';
      // 开始定时请求设备
      startDeviceListTimer();
      break;
  }
};

const onSearch = (val: string) => {
  searchKey.value = val;
  
  // 清除之前的防抖定时器
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer);
  }
  
  // 如果搜索关键词为空，立即执行查询
  if (!val || val.trim() === '') {
    searchLoading.value = false;
    querylog();
    return;
  }
  
  // 显示加载状态
  searchLoading.value = true;
  
  // 设置新的防抖定时器，2秒后执行查询
  searchDebounceTimer = window.setTimeout(() => {
    searchLoading.value = false;
    querylog();
  }, 2000);
};

// 处理搜索框清除事件
const onSearchClear = () => {
  // 清除防抖定时器
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer);
  }
  searchLoading.value = false;
  searchKey.value = '';
  querylog();
};

onMounted(() => {
  customContainer.value = document.querySelector('#debug-select-container');
  // 注册消息处理函数
  window.addEventListener('message', handleMessages);

  // 初始化编辑器
  editor = monaco.editor.create(editorRef.value!, {
    value: '',
    language: 'plaintext',
    theme: props.theme,
    automaticLayout: true,
    minimap: { enabled: false },
    fontSize: 12,
    scrollBeyondLastLine: false,
    lineNumbers: 'off',
    readOnly: true,
    glyphMargin: false,
    folding: false,
    lineDecorationsWidth: 0,
    lineNumbersMinChars: 0,
    renderLineHighlight: 'none',
    overviewRulerBorder: false,
    scrollbar: {
      vertical: 'visible',
      horizontal: 'visible',
      useShadows: false,
      verticalHasArrows: false,
      horizontalHasArrows: false,
      alwaysConsumeMouseWheel: false
    },
    padding: {
      top: 10,
      bottom: 10,
    },
    wordWrap: 'on',
  });

  // 添加滚动事件监听
  const editorDomNode = editor.getDomNode();
  if (editorDomNode) {
    // 监听滚动事件
    editorDomNode.addEventListener('scroll', handleEditorScroll, true);
    
    // 监听鼠标滚轮事件，标记用户正在滚动
    editorDomNode.addEventListener('wheel', () => {
      userScrolling = true;
    }, true);
    
    // 监听鼠标按下事件，可能是用户准备拖动滚动条
    editorDomNode.addEventListener('mousedown', (event) => {
      // 检查是否点击在滚动条上
      const target = event.target as HTMLElement;
      if (target.classList.contains('slider') || 
          target.classList.contains('scrollbar') ||
          target.classList.contains('scroll-decoration')) {
        userScrolling = true;
      }
    }, true);
  }
  
  // 监听键盘事件（上下箭头、Page Up/Down等）
  window.addEventListener('keydown', (event) => {
    switch (event.key) {
      case 'ArrowUp':
      case 'ArrowDown':
      case 'PageUp':
      case 'PageDown':
      case 'Home':
      case 'End':
        userScrolling = true;
        break;
    }
  });

  // 初始化主题
  themeChange();
  
  // 开始请求设备列表
  startDeviceListTimer();
  processOptions.push({ value: '全部进程', label: '全部进程' });
  processValue.value = '全部进程';
});

onBeforeUnmount(() => {
  // 清理资源
  window.removeEventListener('message', handleMessages);
  
  // 清除防抖定时器
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer);
    searchDebounceTimer = null;
  }
  
  // 重置搜索状态
  searchLoading.value = false;
  
  // 清除定时器
  if (deviceTimer !== null) {
    clearInterval(deviceTimer);
    deviceTimer = null;
  }
  
  // 清理滚动事件监听
  if (editor) {
    const editorDomNode = editor.getDomNode();
    if (editorDomNode) {
      editorDomNode.removeEventListener('scroll', handleEditorScroll, true);
      editorDomNode.removeEventListener('wheel', () => { userScrolling = true; }, true);
      editorDomNode.removeEventListener('mousedown', () => { userScrolling = true; }, true);
    }
  }
  
  // 清理键盘事件监听
  window.removeEventListener('keydown', (event) => {
    switch (event.key) {
      case 'ArrowUp':
      case 'ArrowDown':
      case 'PageUp':
      case 'PageDown':
      case 'Home':
      case 'End':
        userScrolling = true;
        break;
    }
  });
  
  // 清理编辑器
  if (editor) {
    editor.dispose();
  }
});

watch(deviceValue, (newDevice) => {
  if (newDevice) {
    // reset process list when device changes
    processOptions.length = 0;
    processOptions.push({ value: '全部进程', label: '全部进程' });
    processValue.value = '全部进程';
    requestProcessList(newDevice);
  }
});

// 请求设备列表
const requestDeviceList = () => {
  // 向VSCode扩展发送获取设备列表的请求
  window.vscode.postMessage({
    command: 'getDeviceList'
  });
};

// 请求进程列表
const requestProcessList = (deviceId: string) => {
  window.vscode.postMessage({
    command: 'getProcessList',
    device: deviceId
  });
};

const themeChange = () => {
  // 响应外部语言变化
  watch(() => props.language, (newVal) => {
    monaco.editor.setModelLanguage(editor.getModel()!, newVal)
  })

  // 响应主题变化
  watch(() => props.theme, (newVal) => {
    monaco.editor.setTheme(newVal)
  })
}

const getDebugOptions = () => {
  debugOptions = [
    'DEBUG',
    'INFO',
    'WARN',
    'ERROR',
    'FATAL',
    'ALL'
  ];
  debugValue.value = 'ALL';
}

const switchChange = (flag: boolean) => {
  saveLogs(flag);
}

//查询日志
const querylog = () => {
  const device = deviceValue.value;
  const process = processValue.value;
  const debug = debugValue.value;
  const wordKey = searchKey.value;
  
  // 清空当前日志内容
  if (editor) {
    editor.setValue('');
  }
  
  // 重置自动滚动状态
  autoScroll = true;
  userScrolling = false;
  
  // 向VSCode扩展发送查询日志的请求
  window.vscode.postMessage({
    command: 'queryLogs',
    device: device,
    process: process,
    logLevel: debug,
    searchKey: wordKey
  });
}

//保存日志
const saveLogs = (flag: boolean) => {
  window.vscode.postMessage({
    command: 'saveLogs',
    enable: flag
  });
}

// 开始设备列表定时请求
const startDeviceListTimer = () => {
  if (deviceTimer === null) {
    // 立即请求一次
    requestDeviceList();
    // 设置定时器，每2秒请求一次
    deviceTimer = window.setInterval(requestDeviceList, 2000);
  }
};

// 停止设备列表定时请求
const stopDeviceListTimer = () => {
  if (deviceTimer !== null) {
    clearInterval(deviceTimer);
    deviceTimer = null;
  }
};

// 检查编辑器是否滚动到底部
const isEditorScrolledToBottom = () => {
  if (!editor) return true;
  
  const scrollHeight = editor.getScrollHeight();
  const scrollTop = editor.getScrollTop();
  const clientHeight = editor.getLayoutInfo().height;
  
  // 如果滚动条位置在最后20像素内，认为已滚动到底部
  return scrollTop + clientHeight >= scrollHeight - 20;
};

// 滚动到底部
const scrollToBottom = () => {
  if (!editor) return;
  
  const scrollHeight = editor.getScrollHeight();
  const clientHeight = editor.getLayoutInfo().height;
  editor.setScrollTop(scrollHeight - clientHeight);
};

// 处理编辑器滚动事件
const handleEditorScroll = () => {
  if (!editor) return;
  
  // 检查是否滚动到底部
  const atBottom = isEditorScrolledToBottom();
  
  // 更新自动滚动状态
  if (atBottom) {
    autoScroll = true;
  } else if (!userScrolling) {
    autoScroll = false;
  }
  
  // 重置用户滚动标志
  userScrolling = false;
};

// 初始化选项
getDebugOptions();
</script>

<style scoped>
.containner {
  margin: 0 auto;
  width: 100%;
  height: calc(100vh - 40px);
  padding: 20px 0;
}

.ml20 {
  margin-left: 20px;
}

.ml5 {
  margin-left: 5px;
}

.width80 {
  width: 80px;
}
.width400 {
 width: 400px;
}
.monaco-editor {
  width: 100%;
  height: calc(100vh - 90px);
  margin: 20px 0;
}
/* 移除编辑器左侧空白区域 */
:deep(#monacoEditorLog .monaco-scrollable-element) {
  left: 0 !important;
  text-align: left;
}

/* 优化日志内容显示 */
:deep(.monaco-editor .view-lines) {
  padding-left: 10px;
}

/* 加载图标旋转动画 */
.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

</style>